<template>
  <!-- 这里v-if是为了防止数据回来之前，商品价格和名称显示为undefined，干脆让数据回来之前，不显示页面结构 -->
  <view v-if="goods_info.goods_name" class="goods-detail-container">
    <!-- 轮播图区域 -->
    <swiper :indicator-dots="true" :autoplay="true" :interval="3000" :duration="1000" :circular="true">
      <swiper-item v-for="(item,i) in goods_info.pics" :key="i">
        <image :src="item.pics_big" @click="preview(i)"></image>
      </swiper-item>
    </swiper>
    <!-- 商品信息区域 -->
    <view class="goods-info-box">
      <!-- 商品价格 -->
      <view class="price">￥{{goods_info.goods_price}}</view>
      <!-- 商品信息主体区域 -->
      <view class="goods_info-body">
        <view class="goods-name">{{goods_info.goods_name}}</view>
        <!-- 收藏 -->
        <view class="favi" @click="collect(goods_info)">
          <uni-icons :type="icon_type" size="18" :color="icon_color"></uni-icons>
          <text>{{icon_text}}</text>
        </view>
      </view>
      <!-- 运费 -->
      <view class="yf">快递：免运费</view>
    </view>
    <rich-text :nodes="goods_info.goods_introduce"></rich-text>
    <!-- 商品导航组件区域 -->
    <view class="goods_nav">
      <uni-goods-nav :fill="true" :options="options" :buttonGroup="buttonGroup" @click="onClick"
        @buttonClick="buttonClick" />
    </view>
  </view>
</template>

<script>
  import { mapState, mapMutations, mapGetters } from 'vuex'
  export default {
    data() {
      return {
        goods_info: {},
        // 底部导航栏中左侧按钮的配置对象
        options: [{
          icon: 'star',
          text: '我的收藏',
        }, {
          icon: 'cart',
          text: '购物车',
          info: 0
        }],
        // 右侧按钮的配置对象
        buttonGroup: [{
            text: '加入购物车',
            backgroundColor: '#ff0000',
            color: '#fff'
          },
          {
            text: '立即购买',
            backgroundColor: '#ffa200',
            color: '#fff'
          }
        ],
        icon_type: 'star', // 收藏后图标类型：star-filled
        icon_color: 'gray', // 收藏后图标颜色：rgb(255,162,0)
        icon_text: '收藏',
        // 倒计时的秒数
        seconds: 3,
        // 定时器的id
        timer: null,
        // 保存当前页的goods_id，用于未登录时，直接点击‘立即购买’按钮，自动跳转到登录页面登录后，重定向到登录前的页面
        goodsId: 0
      };
    },
    async onLoad(options) {
      uni.setNavigationBarTitle({
        title: "商品详情"
      })
      this.goodsId = options.goods_id
      const goods_id = options.goods_id
      // 若该商品已被收藏，则更改收藏图标
      if (this.collection.length !== 0) {
        const result = this.collection.find(item => item.goods_id == goods_id)
        if (result) {
          this.icon_type = 'star-filled'
          this.icon_color = 'rgb(255,162,0)'
          this.icon_text = '已收藏'
        }
      }
      const { data: res } = await uni.$http.get("/api/public/v1/goods/detail", { goods_id })
      if (res.meta.status !== 200) return uni.$showMsg()
      // 解决图片之间的空白间隙
      res.message.goods_introduce = res.message.goods_introduce.replace(/<img /g, '<img style="display:block;"')
      this.goods_info = res.message
    },
    onShow() {
      // 解决在我的收藏页面删除某个商品后，返回该商品详情页时，还显示‘已收藏’的bug
      if (this.goods_info.goods_id) { // 该条件只有在我的收藏页面删除某个商品后，点击左上角返回商品详情页时为true
        const goods_id = this.goods_info.goods_id
        // 若该商品已被取消收藏，则更改收藏图标
        // if (this.collection.length !== 0) {  // 收藏夹中商品个数为0时也执行下边代码
        const result = this.collection.find(item => item.goods_id == goods_id)
        if (result) {
          this.icon_type = 'star-filled'
          this.icon_color = 'rgb(255,162,0)'
          this.icon_text = '已收藏'
          // }
        } else {
          this.icon_type = 'star'
          this.icon_color = 'gray'
          this.icon_text = '收藏'
        }
      }
    },
    methods: {
      ...mapMutations('m_cart', ['addToCart']),
      ...mapMutations('m_user', ['addToCollection', 'delCollection', 'updateRedirectInfo']),
      preview(i) {
        // 预览图片
        uni.previewImage({
          // 预览时，默认显示图片的索引
          current: i,
          // 所有图片url地址的数组
          urls: this.goods_info.pics.map(item => item.pics_big)
        })
      },
      onClick(e) {
        if (e.content.text === "购物车") {
          uni.switchTab({
            url: "/pages/cart/cart"
          })
        }
        if (e.content.text === "我的收藏") {
          if (!this.token) {
            return uni.showToast({
              icon: 'error',
              title: '请登录后查看'
            })
          }
          // 此处为了展示空白收藏夹页面，所以注释掉
          // if (this.collection.length === 0) {
          //   return uni.$showMsg('暂无收藏的商品！')
          // }
          // 跳转到我的收藏页面
          uni.navigateTo({ url: "/subpkg/collect/collect" })
        }

      },
      // 展示倒计时的提示消息
      showTips(n) {
        uni.showToast({
          icon: 'none',
          title: '请登录后再结算！' + n + '秒后自动跳转到登录页',
          mask: true,
          duration: 1500
        })
      },
      // 延时导航到登录页面
      delayNavigate() {
        this.showTips(this.seconds)
        this.timer = setInterval(() => {
          this.seconds--
          if (this.seconds <= 0) {
            clearInterval(this.timer)
            uni.switchTab({
              url: '/pages/my/my',
              success: () => {
                this.updateRedirectInfo({
                  // 跳转方式
                  openType: 'navigateTo',
                  // 从哪个页面跳转过去的
                  from: `/subpkg/goods_detail/goods_detail?goods_id=${this.goodsId}`
                })
              }
            })
            // 重置延迟时间为3，否则，不登录时，第二次点击结算按钮，将不再延时跳转
            return this.seconds = 3 //下边的showTips不再执行
          }
          this.showTips(this.seconds)
        }, 1000)
      },
      async buttonClick(e) {
        if (e.content.text === '加入购物车') {
          // 组织商品的信息对象
          const goods = {
            goods_id: this.goods_info.goods_id,
            goods_name: this.goods_info.goods_name,
            goods_price: this.goods_info.goods_price,
            goods_count: 1,
            goods_small_logo: this.goods_info.goods_small_logo,
            goods_state: true
          }
          this.addToCart(goods)
        }
        if (e.content.text === '立即购买') {
          if (!this.token) return this.delayNavigate()
          // 整理商品数据
          const goods = {
            goods_id: this.goods_info.goods_id,
            goods_name: this.goods_info.goods_name,
            goods_price: this.goods_info.goods_price,
            goods_count: 1,
            goods_small_logo: this.goods_info.goods_small_logo,
            goods_state: true // 因为在商品详情页点击‘直接购买’不需要购物车状态，但是为了和从购物车中购买的商品数据保持一致，此处加上
          }
          // 整理购物车数据（此处只有一个商品）
          const cart = [goods]
          // -------------------------------------------------------------------------------------------
          // 请求商品库存信息，检查要购买的商品是否已经删除、下架、库存不足
          const buyGoods = cart
          // 由于get请求对参数长度有限制，此处buyGoods太长，所以此处使用post请求
          const { data: res } = await uni.$http.post('/api/public/v1/goods/checkgoods', { buyGoods })
          if (res.meta.status !== 200) return uni.$showMsg('获取商品库存信息失败')
          const lastGoods = res.message.lastGoods
          // 首先检查商品是否已删除
          let errMsg = ''
          buyGoods.forEach(item => {
            let result = lastGoods.find(item2 => item2.goods_id === item.goods_id && item2.is_del === 0)
            if (!result) errMsg += `商品（ ${item.goods_name} ）已被删除\n`
          })
          if (errMsg) return uni.$showMsg(errMsg)
          // 商品都存在，接下来检查商品是否已下架
          errMsg = ''
          buyGoods.forEach(item => {
            let result = lastGoods.find(item2 => item2.goods_id === item.goods_id && item2.is_shelf === 1)
            if (!result) errMsg += `商品（ ${item.goods_name} ）已下架\n`
          })
          if (errMsg) return uni.$showMsg(errMsg)
          // 商品都已上架，接下来检查商品库存是否够
          errMsg = ''
          buyGoods.forEach(item => {
            let result = lastGoods.find(item2 => item2.goods_id === item.goods_id && item2.goods_count > item
              .goods_count)
            if (!result) errMsg += `商品（ ${item.goods_name} ）库存不足\n`
          })
          if (errMsg) return uni.$showMsg(errMsg)
          // 至此所有条件验证通过（是否已经删除、下架、库存不足）
          // -------------------------------------------------------------------------------------------
          // 跳转到支付页，传递购物车数据
          uni.navigateTo({
            // 由于购物车数据中有些自己添加的商品的图片是base64格式，在pay页面接收参数时JSON.parse不能够解析base64格式中的特殊字符，
            // 所以此处使用encodeURIComponent加密传输
            url: `/subpkg/pay/pay?cart=${encodeURIComponent(JSON.stringify(buyGoods))}`
          })
        }
      },
      collect(goods_info) {
        if (!this.token) {
          return uni.showToast({
            icon: 'error',
            title: '请先登录'
          })
        }
        // 若用户已登录，更新或取消数据库中该用户收藏商品数据
        if (this.icon_text == '已收藏') {
          // 取消收藏
          this.icon_type = 'star'
          this.icon_color = 'gray'
          this.icon_text = '收藏'
          this.delCollection(goods_info.goods_id)
        } else {
          // 收藏
          this.icon_type = 'star-filled'
          this.icon_color = 'rgb(255,162,0)'
          this.icon_text = '已收藏'
          this.addToCollection(goods_info)
        }
      }
    },
    computed: {
      ...mapState('m_user', ['collection', 'token']),
      ...mapGetters('m_cart', ['total'])
    },
    watch: {
      // 监听商品总个数的变化，使页面上购物车角标及时更新
      total: {
        handler(newValue) {
          const findResult = this.options.find(item => item.text === '购物车')
          if (findResult) {
            findResult.info = newValue
          }
        },
        // 首次加载就触发此监听器，否则刷新后购物车的角标不显示
        immediate: true
      }
    }
  }
</script>

<style lang="scss" scoped>
  .goods-detail-container {
    padding-bottom: 50px;

    swiper {
      height: 750rpx;

      image {
        width: 100%;
        height: 100%;
      }
    }

    .goods-info-box {
      padding: 10px 0px 10px 10px;

      .price {
        color: #c00000;
        font-size: 18px;
        margin: 10px 0;
      }

      .goods_info-body {
        display: flex;
        justify-content: space-between;

        .goods-name {
          width: 288px;
          font-size: 13px;
          margin-right: 10px;
        }

        .favi {
          // width: 120px;
          width: 67px;
          font-size: 12px;
          color: gray;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          border-left: 1px solid #efefef
        }
      }

      .yf {
        font-size: 12px;
        color: gray;
        margin: 10px 0;
      }
    }

    .goods_nav {
      position: fixed;
      bottom: 0;
      left: 0;
      width: 100%;
    }
  }
</style>
